﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKArchKernel.OutWallSearch;
using YJKRGeometry;
using YJKView;

namespace YJKArchMethodLibrary.OutWallSearch
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdOutWallSearchTest2 : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			CmdViewType types = CmdViewType.FloorPlan;
            if (SwitchView.SetUsableView(types, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			this.m_Revit = commandData;
			this.m_Doc = commandData.Application.ActiveUIDocument.Document;
			List<WallData> outWallList = new List<WallData>();
			if (!OutWallFilter.Search(this.m_Doc, this.m_Doc.ActiveView.Id, ref outWallList, true, true))
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (!this.DrawOutWallLocationCurve(outWallList))
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private bool DrawOutWallLocationCurve(List<WallData> outWallList)
		{
			CurveArray curveArray = new CurveArray();
			foreach (WallData wallData in outWallList)
			{
				List<EdgeInfo> outWallSegmentCenterLine = wallData.GetOutWallSegmentCenterLine();
				foreach (EdgeInfo edgeInfo in outWallSegmentCenterLine)
				{
					curveArray.Append(edgeInfo.ConvertToCurve());
				}
			}
			Transaction transaction = null;
			bool result;
			try
			{
				transaction = new Transaction(this.m_Doc);
				transaction.Start("draw out wall location");
				this.m_Doc.Create.NewDetailCurveArray(this.m_Doc.ActiveView, curveArray);
				transaction.Commit();
				result = true;
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted())
				{
					transaction.RollBack();
				}
				result = false;
			}
			return result;
		}

		private ExternalCommandData m_Revit;

		private Document m_Doc;
	}
}
